﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Alex.Library.Log
{
    /// <summary>
    /// 用XML文件保存日志
    /// </summary>
    public class XmlLogger : FileLogger
    {
        #region Ctors

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logDir">存放日志的目录</param>
        /// <param name="ext">日志文件类型</param>
        public XmlLogger(string logDir, string ext) : base(logDir, ext) { }

        /// <summary>
        /// 构造函数，日志文件扩展名默认为.xml
        /// </summary>
        /// <param name="logDir">存放日志的目录</param>
        public XmlLogger(string logDir) : this(logDir, ".xml") { }

        /// <summary>
        /// 从文件日志创建XML日志
        /// </summary>
        /// <param name="logger"></param>
        public XmlLogger(FileLogger logger)
        {
            this.LogDir = logger.LogDir;
            this.Template = logger.Template;
            this.FlushLevel = logger.FlushLevel;
            this.FileExtension = logger.FileExtension;
            this.OverrideIfExist = logger.OverrideIfExist;
            this.Behavior = logger.Behavior;
            this.MaxAchieveSize = logger.MaxAchieveSize;
        }

        /// <summary>
        /// 构造函数，日志存放目录由AppDomain.CurrentDomain.BaseDirectory确定,文件扩展名默认为.xml
        /// </summary>
        public XmlLogger() : this(AppDomain.CurrentDomain.BaseDirectory) { }

        #endregion

        #region Functions

        /// <summary>
        /// 将日志输出到XML文件
        /// </summary>
        /// <param name="level">日志级别</param>
        /// <param name="message">消息</param>
        protected override void DoFlush(LogLevel level, string message)
        {
            ValidateConfig();

            try
            {
                //判断写入的日志文件是使用已有的文件添加还是创建新的文件
                SetFileIfAppendOrNew();

                XmlDocument doc = new XmlDocument();
                XmlElement root = null;
                //如果文件不存在则新建
                if (!File.Exists(this.FullName))
                {
                    XmlNode declare = doc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                    doc.AppendChild(declare);
                    root = doc.CreateElement("logs");
                    doc.AppendChild(root);
                }
                else
                {
                    doc.Load(this.FullName);
                    root = doc.DocumentElement;
                }

                //输出的日志内容
                string content = this.Template.Format(level, message);

                XmlElement el = doc.CreateElement("log");
                //级别属性
                XmlAttribute levelAttr = doc.CreateAttribute("level");
                levelAttr.Value = level.ToString();
                el.Attributes.Append(levelAttr);
                //时间属性
                XmlAttribute timeAttr = doc.CreateAttribute("time");
                timeAttr.Value = String.Format("{0:yyyy/MM/dd HH:mm:ss}", DateTime.Now);
                el.Attributes.Append(timeAttr);                
                //消息
                XmlCDataSection dataNode = doc.CreateCDataSection(content);
                el.AppendChild(dataNode);
                root.AppendChild(el);
                //保存文件
                doc.Save(this.FullName);
            }
            catch (Exception ex)
            {
                //throw ex;
            }
        }

        #endregion
    }
}
